﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;

namespace System.Linq
{
    public static class IEnumerableExtensions
    {
        public static T[] Append<T>(this T[] arrayInitial, params T[] arrayToAppend)
        {
            if (arrayInitial == null) arrayInitial = new T[0];
            T[] ret = new T[arrayInitial.Length + arrayToAppend.Length];
            arrayInitial.CopyTo(ret, 0);
            arrayToAppend.CopyTo(ret, arrayInitial.Length);
            return ret;
        }

        public static List<T> AddExt<T>(this List<T> arrayInitial, params T[] arrayToAppend)
        {
            if (arrayInitial == null) arrayInitial = new List<T>();
            arrayInitial.AddRange(arrayToAppend);
            return arrayInitial;
        }


        public static byte[] XmlSerializeToByte<T>(this T value) where T : class
        {
            if (value == null) return null;

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
                {
                    serializer.Serialize(xmlWriter, value);
                    return memoryStream.ToArray();
                }
            }
        }

        public static T XmlDeserialize<T>(this byte[] value) where T : class
        {
            if (value == null) return null;

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (Stream memoryStream = new MemoryStream(value))
            {
                return (T)serializer.Deserialize(memoryStream);
            }
            return null;
        }
    }
}
